<template>
<div class="face">
  <video id="video" autoplay></video>
  <button @click="toUpload">进行识别</button>
  <transition-group appear tag="ul" class="list">
    <li v-for="item in list" :key="item.id" :class="!item.index?'red':''">{{!item.index?"":"NO."+item.index+ " --- "}}{{item.name}}</li>
  </transition-group>
  <canvas id="canvas" v-show="false"></canvas>
</div>
</template>

<script>
import {
  sign
} from '@/assets/api/moudules/face'
export default {
  name: 'Face',
  data() {
    return {
      canvas: null,
      ctx: null,
      video: null,
      id: 1,
      index: 1,
      list: []
    }
  },
  mounted() {
    this.canvas = document.getElementById('canvas')
    this.ctx = this.canvas.getContext('2d')
    this.video = document.getElementById('video')
    var mediaOpts = {
      audio: false,
      video: true
    }
    navigator.mediaDevices.getUserMedia(mediaOpts).then(this.successFunc).catch(this.errorFunc)
  },
  methods: {
    successFunc(stream) {
      if ('srcObject' in this.video) {
        this.video.srcObject = stream
      } else {
        this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream
      }
    },
    errorFunc(err) {
      alert(err.name)
    },
    addListFail(name) {
      this.list.unshift({
        id: this.id,
        index: '',
        name
      })
      this.id++
    },
    addListScuess(name, data) {
      this.list.unshift({
        id: this.id,
        index: this.index,
        name: `${name}\t${data.signTime}`
      })
      this.index++
      this.id++
    },
    toUpload() {
      this.canvas.width = this.video.clientWidth
      this.canvas.height = this.video.clientHeight
      this.ctx.drawImage(this.video, 0, 0, this.video.clientWidth, this.video.clientHeight)
      const arr = this.canvas.toDataURL('image/png').split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      var obj = new Blob([u8arr], {
        type: mime
      })
      const param = new FormData()
      param.append('file', obj)
      sign(param).then(res => {
        if (res.code === 0) {
          this.addListFail(res.msg)
        } else if (res.code === 200) {
          this.addListScuess(res.msg, res.data)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.face {
  height: calc(100vh - 50px);
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;

  #video {
    width: 100vw;
  }

  .list {
    height: 200px;
    padding: 20px;
    text-align: center;
    font-size: $font-size-medium-s;
    list-style-type: none;
    background-color: #fff;
    overflow-y: auto;

    .red {
      color: #f00;
      font-size: $font-size-medium-s;
    }
  }

  .v-move {
    transition: all 0.6s ease;
  }

  .v-leave-active {
    position: absolute;
  }
}
</style>
